package com.service;

import static com.def.GenericDef.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dao.IRetBoxDao;
import com.dao.IRetPrdInfoDao;
import com.dao.IRetWODao;
import com.icim.service.ICIMBaseService;
import com.mapKeyVal.key.PalletKey;
import com.mapKeyVal.key.StatBoxOpeBnklotKey;
import com.model.Ret_box;
import com.model.Ret_prd_info;
import com.model.Ret_wo;
import com.tx.Xpinqpalt.XpinqpaltI;
import com.tx.Xpinqpalt.XpinqpaltO;
import com.tx.Xpinqpalt.XpinqpaltOA;
import com.tx.Xpinqpalt.XpinqpaltOB;
import com.util.MqOpe;
import com.util.Util;

@Scope("prototype")
@Service("XpinqpalletService")
public class XpinqpalletService extends ICIMBaseService{
	private static Logger logger = Logger.getLogger(XpinqpalletService.class);
	private static String TX_NAME = T_XPINQPALT;
	
	@Autowired
	private XpinqpaltI inTrx;
	@Autowired
	private XpinqpaltO outTrx;

	@Autowired
	private IRetPrdInfoDao retPrdInfoDao;
	@Autowired
	private IRetBoxDao retBoxDao;
	@Autowired
	private IRetWODao retWoDao;
	
	private String gszMsgBuf = "";

	public String subMainProc(String strInMsg) {
		long rtnCode = _NORMAL;
		gszMsgBuf = "";
		String outMsg = "";
		outTrx.setTrx_id(TX_NAME);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));

		MqOpe mqOpe = new MqOpe();

		try {
			inTrx = (XpinqpaltI) mqOpe.inStr2Obj(strInMsg, inTrx);
			logger.info("InTrx is " + strInMsg);

			rtnCode = subMainProc2(inTrx.getAction_flg().toCharArray()[0]);
			if (rtnCode != _NORMAL) {
				outTrx.setRtn_code(String.valueOf(rtnCode));
				outTrx.setRtn_mesg(gszMsgBuf);
				TransactionAspectSupport.currentTransactionStatus()
						.setRollbackOnly();
			} else {
				outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
				outTrx.setRtn_mesg(RETURN_MESG_OK);
				retPrdInfoDao.flushCurSession();
			}
		} catch (Exception ex) {
			outTrx.setRtn_mesg(ex.toString());
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			logger.error(Util.stackTraceToString(ex));
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
		} finally {
			outMsg = mqOpe.obj2Str(outTrx);
			logger.info(outMsg);
		}
		return outMsg;
	}

	private long subMainProc2(char actionType) {
		long rtnCode = _NORMAL;

		switch (actionType) {
			case 'P':{
				rtnCode = getPalletInfoByBoxId();
				break;
			}
			case 'Q':{
				rtnCode = getBoxinfoByPallet();
				break;
			}
			default: {
				gszMsgBuf = "Invalide type input: [" + actionType + "]";
				return E_XPINQBOX_INVALID_INPUT;
			}
		}
		return rtnCode;
	}

	/**
	 * 4400箱号获取栈板信息，for 其他客户栈板标签
	 * 
	 * @return
	 */
	private long getPalletInfoByBoxId() {
		long lRc = _NORMAL;
		Map<PalletKey, String> palletMap = new HashMap<PalletKey, String>();
		StringBuffer sbBox = new StringBuffer();
		for(int i=0; i<inTrx.getIary().size(); i++){
			sbBox.append("'").append(inTrx.getIary().get(i).getBox_id()).append("',");
		}
		sbBox = sbBox.deleteCharAt(sbBox.length()-1);
		String sql = "SELECT IFNULL(B.MDL_CATE_FK,'') AS MDL_CATE, IFNULL(A.MDL_ID_FK,'') AS MDL_ID_FK, IFNULL(A.COUNT,0) AS COUNT , IFNULL(A.DN_NO,'') AS DN_NO, " 
			+ "IFNULL(B.CUS_INFO_FST,'') AS CUS_INFO_FST, IFNULL(B.CUS_INFO_SND,'') AS CUS_INFO_SND, IFNULL(A.PALLET_ID ,'') AS PALLET_ID,IFNULL(A.BOX_ID_FK,'') AS BOX_ID_FK "
			+ "FROM (SELECT MDL_ID_FK,DN_NO,WO_ID_FK,PALLET_ID,BOX_ID_FK,COUNT(*) AS COUNT FROM RET_PRD_INFO WHERE BOX_ID_FK IN ("
			+ sbBox.toString() + ") GROUP BY MDL_ID_FK,DN_NO,WO_ID_FK,PALLET_ID,BOX_ID_FK) A "
			+ "LEFT JOIN (SELECT WO_ID,MDL_CATE_FK,CUS_INFO_FST,CUS_INFO_SND FROM RET_WO WHERE WO_ID IN (SELECT DISTINCT WO_ID_FK FROM RET_BOX WHERE BOX_ID IN("
			+ sbBox.toString() + "))) B "
			+ "ON A.WO_ID_FK=B.WO_ID";
		
		List<Object[]> palletInfoList  =  retPrdInfoDao.findBySQL(sql);
		for(int i=0; i<palletInfoList.size(); i++){
			Object pallet[] = palletInfoList.get(i);
			PalletKey palletKey = new PalletKey(pallet[0].toString(),pallet[1].toString(),pallet[3].toString(),pallet[4].toString(),pallet[5].toString(),pallet[6].toString());
			if (palletMap.containsKey(palletKey)) {
				palletMap.put(palletKey, palletMap.get(palletKey) + "&" + pallet[7].toString() + "@" + Integer.valueOf(pallet[2].toString()));
			} else {
				palletMap.put(palletKey, pallet[7].toString()+ "@" + Integer.valueOf(pallet[2].toString()));
			}
		}
		
		//set oary
		Iterator<Entry<PalletKey, String>> iter = palletMap.entrySet().iterator();
		List<XpinqpaltOA> oaryList = new ArrayList<XpinqpaltOA>();
		PalletKey key = null;
		while(iter.hasNext()){
			StringBuffer boxIds = new StringBuffer();
			Integer count = 0;
			Entry<PalletKey, String> entry = iter.next();
			key = entry.getKey();
			String pallet = palletMap.get(key);
			String[] boxInfos = pallet.split("&");
			for(int i=0; i<boxInfos.length; i++){
				String[] boxInfo = boxInfos[i].split("@");
				boxIds.append(boxInfo[0]).append("、");
				count = count + Integer.valueOf(boxInfo[1].toString());
			}
			XpinqpaltOA oary = new XpinqpaltOA();
			oary.setMdl_cate(key.getMdl_cate_fk());
			oary.setMdl_id(key.getMdl_id_fk());
			oary.setCount(count.toString());
			oary.setDn_no(key.getDn_no());
			oary.setCus_info_fst(key.getCus_info_fst());
			oary.setCus_info_snd(key.getCus_info_snd());
			oary.setPallet_id(key.getPallet_id());
			oary.setBoxIds(boxIds.deleteCharAt(boxIds.length()-1).toString());
			oaryList.add(oary);
		}
		outTrx.setPallet_cnt(oaryList.size());
		outTrx.setOary(oaryList);
		return lRc;
	}
	
	/**
	 * 4400箱号获取栈板信息，for 007
	 * 
	 * @return
	 */
	private long getBoxinfoByPallet() {
		long lRc = _NORMAL;
		if (Util.isSpaceCheck(inTrx.getPallet_id())) {
			gszMsgBuf = "Input pallet id [" + inTrx.getPallet_id() + "] is null!";
			return E_XPINQBOX_INVALID_INPUT_BOX_ID;
		}
        String palletId = inTrx.getPallet_id();
		String hql = "FROM Ret_box where pallet_id_fk='" + palletId + "'";
		
		List<XpinqpaltOB> oaryList = new ArrayList<XpinqpaltOB>();
		List<Ret_box> boxList = new ArrayList<Ret_box>();
		boxList = retBoxDao.find(hql);
		if(boxList.size()==0){
			gszMsgBuf = "栈板 [" + inTrx.getPallet_id() + "] 中没有箱子!";
			return E_XPINQBOX_INVALID_INPUT_BOX_ID;
		}else{
			for(Ret_box retBox : boxList){
				XpinqpaltOB oary2 = new XpinqpaltOB();
				//prdinfo
				Integer mode_cnt = 0;
				List<Ret_prd_info> ret_prd_infoList = new ArrayList<Ret_prd_info>();
				// Get prd info
				ret_prd_infoList = retPrdInfoDao.getShtListInfo(retBox.getBox_id());
				if(ret_prd_infoList != null){
					mode_cnt = ret_prd_infoList.size() * ret_prd_infoList.get(0).getX_axis_cnt_fk() * ret_prd_infoList.get(0).getY_axis_cnt_fk();
				}
				//end
				if(!Util.isSpaceCheck(retBox.getWo_id_fk())){
					Ret_wo ret_wo = new Ret_wo();
					ret_wo = retWoDao.get(retBox.getWo_id_fk());
					if(null != ret_wo ){
						oary2.setCus_id(ret_wo.getCus_id_fk());
						oary2.setTo_thickness(ret_wo.getTo_thickness().toString());
						if(!Util.isSpaceCheck(ret_wo.getCut_mdl_id_fk())){
							oary2.setFinal_mdl(ret_wo.getCut_mdl_id_fk());
						}else if(!Util.isSpaceCheck(ret_wo.getFm_mdl_id_fk())){
							oary2.setFinal_mdl(ret_wo.getFm_mdl_id_fk());
						}else{
							oary2.setFinal_mdl(ret_wo.getTh_mdl_id_fk());
						}
						oary2.setCus_mtrl_id(ret_wo.getCus_mtrl_id_fk());
						oary2.setGlass_from(ret_wo.getGlass_from());
						if(null != ret_wo.getSo_id()){
							Ret_wo retSo = new Ret_wo();
							retSo = retWoDao.get(ret_wo.getSo_id());
							if(null != retSo){
								oary2.setMtrl_part(retSo.getMtrl_part());
								oary2.setReal_so(retSo.getSo_id());
							}
						}
					}
				}
				
				oary2.setBox_id(retBox.getBox_id());
				oary2.setPallet_id(retBox.getPallet_id_fk());
				oary2.setPhy_pallet_id(retBox.getExt_11());
				oary2.setPrd_qty(retBox.getPrd_qty().toString());
				oary2.setWo_id(retBox.getWo_id_fk());
				oary2.setSo_id(retBox.getSo_id_fk());
				oary2.setMode_cnt(mode_cnt.toString());
				oaryList.add(oary2);
			}
		}
		outTrx.setOary2(oaryList);
		return lRc;
	}
}
